package cn.cas.mango.service;

import cn.cas.mango.dto.HotListDetail;
import cn.cas.mango.dto.Message;
import cn.cas.mango.dto.param.SummaryParam;
import cn.cas.mango.util.RequestUtil.GetIdsRequest;
import cn.cas.mango.util.TimeUtil;
import cn.cas.mango.util.string.StringUtils;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SummaryService {
  @Autowired
  ConfigService configService;
  @Autowired
  GetIdsRequest getIdsRequest;
  @Autowired
  ElasticsearchClient elasticsearchClient;

  @Autowired
  ModelService modelService;
  public Message getSummary(SummaryParam summaryParam) {
    String ids = summaryParam.getIds();
    summaryParam.setUuid(StringUtils.getUUID());
    if (Strings.isBlank(ids)) {
      return Message.builder().msg("id为空").data(new JSONObject()).build();
    }
    String[] idsArray = ids.split(",");
    List<String> idsList = new ArrayList<>(idsArray.length);
    idsList.addAll(Arrays.asList(idsArray));
    SearchRequest r = getIdsRequest.getIds(idsList);
    SearchResponse<HotListDetail> search;
    TimeUtil timeUtil = new TimeUtil();
    try {
      search = elasticsearchClient.search(r, HotListDetail.class);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    log.info("[uuid {}], get data cost: {}s", summaryParam.getUuid(), timeUtil.getCost());
    List<HotListDetail> list = search.hits().hits().stream().map(x -> x.source()).collect(Collectors.toList());
    timeUtil.setStart();
    JSONObject dataOb = modelService.getModelSummary(list);
    Double cost = timeUtil.getCost();
    log.info("[uuid {}], get model summary cost: {}s", summaryParam.getUuid(), cost);
    String data = dataOb.getString("data");
    log.info("[uuid {}], summary: {}", summaryParam.getUuid(), data);
    log.info("[uuid {}], start writing to file", summaryParam.getUuid());
    JSONObject jsonObject = wrap2FileObject(list, data, cost);
    appendToFile("history.txt", jsonObject.toJSONString());
    log.info("[uuid {}], stop writing to file", summaryParam.getUuid());
    return Message.builder().data(data).msg("成功").code(200).build();
  }

  JSONObject wrap2FileObject(List<HotListDetail> list, String summary, Double cost) {
    JSONObject ret = new JSONObject();
    ret.put("summary", summary);
    JSONArray dataArray = new JSONArray();
    for (HotListDetail hotListDetail: list) {
      JSONObject temp = new JSONObject();
      temp.put("time", hotListDetail.getInsert_time());
      temp.put("title", hotListDetail.getTitle());
      temp.put("desc", hotListDetail.getDesc());
      temp.put("cost", cost);
      dataArray.add(temp);
    }
    ret.put("data", dataArray);
    return ret;
  }
  public static void appendToFile(String filePath, String content) {
    try (FileWriter fw = new FileWriter(filePath, true)) {
      fw.write(content + "\n");
      fw.flush();
    } catch (IOException e) {
      log.error("error writing to file", e);
    }
  }
}
